#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
AppEngine-Base-Twitter
 
Twitter API wrapper for applications on Google App Engine
 
See: http://0-oo.net/sbox/python-box/appengine-twitter
License: http://0-oo.net/pryn/MIT_license.txt (The MIT license)
Modified by Kavin Gray
'''
__author__ = 'dgbadmin@gmail.com'
__edit__ = 'grayseason@gmail.com'
 
 
import base64
from google.appengine.api import xmpp
import urllib,urllib2,re
from django.utils import simplejson
from google.appengine.api import urlfetch
 
 
class AppEngineSina(object):
  
  def __init__(self, tw_name='', tw_pswd=''):
    '''
    Note: Some actions require password or OAuth.
    '''
    self._api_url = 'http://api.t.sina.com.cn/'
    self.tw_name = tw_name
    self._oauth = None
    self._app_key = xxxxxxx #ur sina app key

    self._headers = {}
    if tw_pswd != '':
      auth = base64.encodestring(tw_name + ':' + tw_pswd)[:-1]
      self._headers['Authorization'] = 'Basic ' + auth
 
 
  # ========= Status Methods ===========
 
  def update(self, msg):
    '''
    Post a msg
    Sucess => Retrun 200
    Fialed => Return other HTTP status
    '''        
    return self._post('/statuses/update.json', {'status': msg,'source':self._app_key})


  def comment(self, msg_id, msg):
    '''
    Post a comment
    Sucess => Retrun 200
    Fialed => Return other HTTP status
    '''        
    return self._post('/statuses/comment.json', {'id': msg_id,'comment': msg,'source':self._app_key})




  def getContent(self):
    '''
    return the content
    '''
    return self.content




  # ========= Timeline Methods =========

  def user_timeline(self, page=0):
    '''
    get user Timeline  
    Sucess => Return contents of user timeline /
    Fialed => Return error HTTP status
    '''
    if(page==0):
        status = self._get('/statuses/user_timeline.json', {"count":10,'source':self._app_key})
    else:
        status = self._get('/statuses/user_timeline.json', {"page": page,'source':self._app_key})
    if(status==200):
        self.content=self.last_response.content
    return status  


  def home_timeline(self, msgid=0, page=0):
    '''
    save and get home timeline
    Sucess => Return contents of home timeline
    Failed => Return other HTTP status
    '''
    if(msgid==0):
        if(page==0):
            status = self._get('/statuses/home_timeline.json', {"count":10,'source':self._app_key})
        else:
            status = self._get('/statuses/home_timeline.json', {"page":page,'source':self._app_key})
    else:
        status = self._get('/statuses/home_timeline.json', {"since_id":msgid,'source':self._app_key})
    if status == 200:
      self.content=self.last_response.content
    return status


      
  def friends_timeline(self , msgid=0):
    '''
    save and get friends timeline
    Sucess => Return contents of friends timeline
    Failed => Return other HTTP status
    '''
    if(msgid==0):
        count=10
        status = self._get('/statuses/friends_timeline.json', {"count":count,'source':self._app_key})
    elif(msgid==1):
        count=20
        status = self._get('/statuses/friends_timeline.json', {"count":count,'source':self._app_key})
    else:
        status = self._get('/statuses/friends_timeline.json', {"since_id":msgid,'source':self._app_key})
    if status == 200:
      self.content=self.last_response.content
    return status


  def mentions(self, msgid=0,page=0):
    '''
    get and save Mention messages
    Sucess => Return content of mentions
    Fialed => Return other HTTP status
    '''
    if(msgid==0):
        if(page==0):
            status = self._get('/statuses/mentions.json', {"count":10,'source':self._app_key})
        else:
            status = self._get('/statuses/mentions.json', {"page":page,'source':self._app_key})
    else:
        status = self._get('/statuses/mentions.json', {"since_id":msgid,'source':self._app_key})        
    if(status==200):
        self.content=self.last_response.content
    return status



  # ========= Direct Message Methods =========
  
  def getDMessage(self,dmid=0):
    '''
    get and save Direct Messages
    Sucess => Return content of Direct Message
    Fialed => Return other HTTP status
    '''
    status = self._get('/direct_messages.json', {"since_id":dmid,'source':self._app_key})
    if(status==200):
        self.content=self.last_response.content
    return status



  def sentDMessage(self, name ,text):
    '''
    Sent a Direct Messages
    Sucess => Retrun 200
    Fialed => Return other HTTP status
    '''
    return self._post('/direct_messages/new.json', {'screen_name': name,'text': text,'source':self._app_key})



 
 
  # =========  Private methods  =========  
 
  def _post(self, path, params):
    url = self._api_url + path
    res = urlfetch.fetch(url=url,
                         payload=urllib.urlencode(params),
                         method='POST',
                         headers=self._headers)
    self.last_response = res
    return res.status_code


    
  def _get(self, path, params):
    url = self._api_url + path
    url += '?' + urllib.urlencode(params)
    res = urlfetch.fetch(url=url, method='GET', headers=self._headers)
    self.last_response = res
    return res.status_code
 

